package com.whereareyou.service.impl;

import com.whereareyou.model.Position;
import com.whereareyou.service.PositionService;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * Created by 家玮 on 2014/7/28.
 */
public class PositionServiceImpl implements PositionService {
    private final EntityManager entityManager;

    @Inject
    public PositionServiceImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }


    @Override
    public Position getPoiIn5Minute(String userId) {
        Query query = entityManager.createQuery("select p from Position p where p.user.id = :userId and p.dateCreated >= :time order by p.dateCreated desc");
        query.setMaxResults(1);
        query.setParameter("userId", userId);
        query.setParameter("time", Date.from(Instant.now().minus(Duration.ofMinutes(5))));
        try {
            return  (Position) query.getSingleResult();
        }catch (NoResultException exception){
            return null;
        }
    }
}
